import React from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Icon,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
  Input,
  Divider,
  message,
  Upload,
  Modal,
  List,
  Switch,
  notification,
  Popover
} from 'antd';

import { StyleSheet, css } from 'aphrodite';

import { swap } from 'react-magic';
import styles from './AddNewContact.less';
import { getValueWithLocalStorage } from '@/utils/authority';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const { MonthPicker, RangePicker } = DatePicker;

import  config from '../../../config/web.config'

const styles_animation = StyleSheet.create({
  magic: {
    animationName: swap,
    animationDuration: '1s',
  },
});

import moment from 'moment';

import { connect } from 'dva';

const namespace = 'ContactList';

const dateFormat = 'YYYY-MM-DD';


const userInfo = getValueWithLocalStorage('userinfo');

import router from 'umi/router';

const mapStateToProps = state => {
  const ret = state[namespace].ret;
  const isLoading = state[namespace].isLoading;

  return {
    ret,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    saveContact: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/saveContact`,
        payload: {
          ...para,
          saveContactCallback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },
    editContact: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/editContact`,
        payload: {
          ...para,
          onEditContactCallback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },
  };
};
@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class AddNewContact extends React.Component {
  constructor(props) {
    super(props);

    const isNew =  this.props.location.query.name == undefined
    const  registertime = isNew? moment().format('YYYY-MM-DD') :(this.props.location.query.carregistertime == 'NaN-aN-aN' || this.props.location.query.carregistertime == '' ? moment().format('YYYY-MM-DD'):this.props.location.query.carregistertime)
    this.state = {
      id: isNew ? '' : this.props.location.query._id,
      h_picList:
        isNew
          ? []
          : [
            {
              uid: '1',
              name: 'hd_h.png',
              status: 'done',
              url:config.HttpUrl+'/file/pic/'+this.props.location.query.headurl,
            },
          ],
      headurl: isNew ? '' : (this.props.location.query.headurl == null?'':(this.props.location.query.headurl.indexOf(".png") != -1  ? this.props.location.query.headurl:this.props.location.query.headurl+'.png')),
      carcode: isNew ? '' : this.props.location.query.carcode,
      name:isNew? '' : this.props.location.query.name,
      tel:isNew? '' : this.props.location.query.tel,
      cartype: isNew? '' : this.props.location.query.cartype,
      isbindweixin: isNew? '0' : this.props.location.query.isbindweixin,
      vin: isNew? '' : this.props.location.query.vin,
      carregistertime: registertime,
      safecompany: isNew? '' : this.props.location.query.safecompany,
      safenexttime: isNew? moment().format('YYYY-MM-DD') : (this.props.location.query.safenexttime === 'NaN-aN-aN'|| this.props.location.query.safenexttime == '' ? moment().format('YYYY-MM-DD'):this.props.location.query.safenexttime),
      yearchecknexttime: isNew? moment().format('YYYY-MM-DD') : (this.props.location.query.yearchecknexttime === 'NaN-aN-aN' || this.props.location.query.yearchecknexttime == ''? moment().format('YYYY-MM-DD'):this.props.location.query.yearchecknexttime),
      isVip: isNew? '0' : this.props.location.query.isVip,
      tqTime1: isNew? '0' : this.props.location.query.tqTime1,
      tqTime2: isNew? '0' : this.props.location.query.tqTime2,
      inserttime:  isNew
        ? moment().format('YYYY-MM-DD')
        : (this.props.location.query.starttime === 'NaN-aN-aN'|| this.props.location.query.starttime == '' ? moment().format('YYYY-MM-DD'):this.props.location.query.starttime),
      isNew: isNew,
      isShowCarTypeSelectView:false,
    };
  }

  /*****************************model's callback********************************/

  saveContactCallback = res => {
    if (res.code == 0) {
      message.error(res.msg);
    } else {
      message.success(res.msg);
      router.push('/contact/contactList');
    }
  };

  /**
   * 编辑保存的回调
   * @param res
   */
  onEditsaveContactCallback = res => {
    if (res.code == 0) {
      message.error(res.msg);
    } else {
      message.success(res.msg);
      router.push('/contact/contactList');
    }
  };

  componentDidMount = () => {


    /**
     * 选车型->iframe+跨域处理数据交互
     */
    window.addEventListener('message', (e)=>{
      var data = e.data;
      this.setState({
        cartype:data,
        isShowCarTypeSelectView:false})
    }, false);

  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleChange1 = ({ file, fileList, event }) => {
    if (file.status == 'done') {
      message.success('图片上传成功');
    }
    this.setState({ h_picList: fileList,headurl: file.response == undefined ? '' :file.response.ret.url});
  };

  beforeUpload1 = (file, fileList) => {
    const isJPG =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJPG) {
      message.error('只能上传.jpeg,png,jpg格式的图片');
      notification.open({
        message: '上传失败',
        description: '只能上传.jpeg,png,jpg格式的图片',
      });
      setTimeout(() => {
        this.setState({ h_picList: [] });
      }, 500);
    }

    const isLt2M = file.size / 1024 < 500;
    if (!isLt2M) {
      alert('图片需要小于500k!');
      setTimeout(() => {
        this.setState({ h_picList: [] });
      }, 500);
    }
    return isLt2M;
  };

  render() {
    var that = this;

    const topContent = (
      <Row className={styles.row} gutter={10}>
        <Col span={3}>
          <span className={styles.tipLab}>选择活动类型</span>
        </Col>
        <Col span={10}>
          <RadioGroup
            className={styles.typeBg}
            defaultValue={that.state.type}
            onChange={e => {
              that.setState({ type: parseInt(e.target.value) }, () => {
                if (parseInt(that.state.type) == 0) {
                  message.success('当前活动类型是:普通宣传活动');
                } else if (parseInt(that.state.type) == 1) {
                  message.success('当前活动类型是:注册登记活动');
                }
              });
            }}
          >
            <RadioButton value="0">普通宣传活动</RadioButton>
            <RadioButton value="1">注册登记活动</RadioButton>
          </RadioGroup>
        </Col>
      </Row>
    );

    const NUM_TITLE = 20;
    const NUM_TITLEDESC = 30;
    const NUM_CONTENT = 140;
    const NUM_PIC = 1;
    const userInfo = getValueWithLocalStorage('userinfo');
    const { previewVisible, previewImage } = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const dateFormat = 'YYYY-MM-DD';

    return (
      <Card title={that.state.isNew ? '新增客户' : '编辑客户'} bordered={false}>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>车主姓名</span>
          </Col>
          <Col span={5}>
            <Input
              defaultValue={that.state.name}
              onChange={e => {
                that.setState({ name: e.target.value });
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>车牌号</span>
          </Col>
          <Col span={5}>
            <Input
              defaultValue={that.state.carcode}
              onChange={e => {
                that.setState({ carcode: e.target.value });
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>车主号码</span>
          </Col>
          <Col span={5}>
            <Input
              defaultValue={that.state.tel}
              onChange={e => {
                that.setState({ tel: e.target.value });
              }}
            />
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>车架号</span>
          </Col>
          <Col span={5}>
            <Input
              defaultValue={that.state.vin}
              onChange={e => {
                that.setState({ vin: e.target.value });
              }}
            />
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>车型</span>
          </Col>
          <Col span={5}>
            <Popover
                      visible={that.state.isShowCarTypeSelectView}
                      placement="topLeft"
                      content={<iframe id="google_ads_frame2" name="google_ads_frame2" width="300" height="500" frameborder="0"  marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" src={config.HttpUrl+'/noticeboard/carpick4web'}/>}
                      title="选择车型"
                      trigger="click"
                      onVisibleChange={(state)=>{
                        if(!state){

                        }
                      }}
            >
            <Input
              disabled={true}
              defaultValue={that.state.cartype}
              onChange={e => {
                that.setState({ cartype: e.target.value });
              }}
            />
            </Popover>
          </Col>
          <Button type="primary" onClick={()=>{
            that.setState({
              isShowCarTypeSelectView: true,
            });
          }}>+</Button>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>头像</span>
          </Col>
          <Col span={18}>
            <Upload
              data={{
                fileName: moment().format('YYYY-MM-DD HH:mm:ss:SSS'),
                tel: userInfo.tel,
              }}
              headers={{ tel: userInfo.tel, type: 0 }}
              action={'/web/file/picUploadWebContact?' + 'tel=' + userInfo.tel}
              listType="picture-card"
              fileList={that.state.h_picList}
              beforeUpload={this.beforeUpload1}
              onPreview={this.handlePreview}
              onChange={this.handleChange1}
              className="avatar-uploader"
            >
              {that.state.h_picList.length == NUM_PIC ? null : uploadButton}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>车辆注册时间</span>
          </Col>
          <Col span={5}>
            <DatePicker
              allowClear={false}
              value={moment(that.state.carregistertime, dateFormat)}
              onChange={(date, dateString) => {
                that.setState({
                  carregistertime:dateString
                });
              }}
            />
          </Col>

        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>下次年审时间</span>
          </Col>
          <Col span={5}>
            <DatePicker
              allowClear={false}
              value={moment(that.state.yearchecknexttime, dateFormat)}
              onChange={(date, dateString) => {
                that.setState({
                  yearchecknexttime:dateString
                });
              }}
            />
          </Col>

          <Col span={3}>
            <span className={styles.tipLab}>提前提醒天数</span>
          </Col>
          <Col span={2}>
            <Input
              defaultValue={that.state.tqTime1}
              onChange={e => {
                that.setState({ tqTime1: e.target.value });
              }}
            />
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>保险公司</span>
          </Col>
          <Col span={5}>
            <Input
              defaultValue={that.state.safecompany}
              onChange={e => {
                that.setState({ safecompany: e.target.value });
              }}
            />
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>保险到期时间</span>
          </Col>
          <Col span={5}>
            <DatePicker
              allowClear={false}
              value={moment(that.state.safenexttime, dateFormat)}
              onChange={(date, dateString) => {
                that.setState({
                  safenexttime:dateString
                });
              }}
            />
          </Col>

          <Col span={3}>
            <span className={styles.tipLab}>提前提醒天数</span>
          </Col>
          <Col span={2}>
            <Input
              defaultValue={that.state.tqTime2}
              onChange={e => {
                that.setState({ tqTime2: e.target.value });
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={48}>
          <Col offset={3} span={18}>
            <Button
              type="primary"
              block
              onClick={() => {

                if(that.state.name.length == 0){
                  message.error('客户名不能为空')
                  return
                }

                if(that.state.tel.length == 0){
                  message.error('客户号码不能为空')
                  return
                }

                if(that.state.vin.length == 0){
                  message.error('vin码不能为空')
                  return
                }

                if(that.state.carcode.length == 0){
                  message.error('车牌号不能为空')
                  return
                }

                if(that.state.cartype.length == 0){
                  message.error('车型不能为空')
                  return
                }

                if (that.state.isNew) {
                  that.props.saveContact(that.state, userInfo.tel, that.saveContactCallback);
                } else {
                  this.props.editContact(
                    this.state,
                    userInfo.tel,
                    that.onEditsaveContactCallback
                  );
                }
              }}
            >
              {that.state.isNew ? '发布' : '保存编辑'}
            </Button>
          </Col>
        </Row>
      </Card>
    );
  }
}
